// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
import NewsDetail from '../pages/NewsDetail'

// 创建一个路由器
const router = new VueRouter({
  mode: 'history', // 默认hash 兼容性好 hash-不作为路径传递，history兼容性略差
  routes: [
    {
      name: 'guanyu',
      path: '/about',
      component: About,
      meta: {isAuth: true,title: '关于'}
    },
    {
      name: 'zhuye',
      path: '/home',
      component: Home,
      meta: {title: '主页'},
      children: [
        {
          name: 'xinwen',
          path: 'news',
          component: News,
          meta: {isAuth: true, title: '新闻'},
          beforeEnter: (to, from, next) => {
            console.log('beforeEnter')
            if(to.meta.isAuth){
              if(localStorage.getItem('school') === 'xiaoxiao') {
                next()
              } else {
                alert('学校名不对，无权限查看！')
              }
            } else {
              next()
            }
          },
          children: [
            {
              name: 'xinwenxiangqing',
              path: 'newsdetail/:id/:title',
              component: NewsDetail,
              meta: {isAuth: true, title: '新闻详情'},
              // props的第一种写法，值为对象，该对象中的所有key-value都会通过props传给Detail组件
              // props: {a: 1, b: 'hello'}
              // props的第二种写法，值为布尔值，若布尔值为真，就会把路由组件收到的所有params参数，以props的形式传给Detail组件
              // props: true,
              // props的第三种写法，值为函数，该函数返回的对象中每一组key-value都会通过props传给Detail组件
              props($route) {
                return {id: $route.params.id, title: $route.params.title}
              }
            }
          ]
        },
        {
          name: 'xiaoxi',
          path: 'message',
          component: Message,
          meta: {isAuth: true, title: '消息'},
          children: [
            {
              name: 'xiangqing',
              path: 'detail',
              component: Detail,
              meta: {isAuth: true, title: '消息详情'},
              // props({query: {id, title}}) { // 解构赋值的连续写法，这里写语义化不明确，不推荐使用
              //   return {id, title}
              // }
              props({query}) {
                return {id: query.id, title: query.title}
              }
            }
          ]
        }
      ]
    }
  ]
})
/*
// 全局前置路由守卫——初始化的时候被调用，每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  console.log('前置路由守卫', to, from)
  // if(to.path === '/home/news' || to.path === '/home/message'){
  // if(to.name === 'xinwen' || to.name === 'xiaoxi'){
  if(to.meta.isAuth){
    if(localStorage.getItem('school') === 'xiaoxiao') {
      next()
    } else {
      alert('学校名不对，无权限查看！')
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  console.log('后置路由守卫', to, from)
  document.title = to.meta.title || 'vue_test'
})
*/
export default router